<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <el-button type="primary" icon="el-icon-search" @click="TableSearch">搜 索</el-button>
                <el-button @click="Reset" icon="el-icon-delete">重 置</el-button>
                <!-- <el-button type="success" icon="el-icon-upload2" @click="handleImport">导 入</el-button> -->
                <el-button type="warning" icon="el-icon-download" @click="handleExport">导出记录</el-button>
            </div>
            <div class="tb-body">
                <el-form ref="searchFormRef" :model="searchForm" :inline="true" label-width="120px" :style="`flex:1;`">
                    <el-form-item label="用户">
                        <el-paged-select :where="{ RoleType: 1 }" url="/User/List" columnName="Name" columnValue="Id"
                            v-model="searchForm.UserId">
                        </el-paged-select>
                    </el-form-item>
                    <el-form-item label="班级">
                        <el-paged-select url="/Organization/List" columnName="Name" columnValue="Id" @input="GetCheckCourse"
                            v-model="searchForm.OrganizationId">
                        </el-paged-select>
                    </el-form-item>

                    <el-form-item label="打卡时间">
                        <el-date-picker v-model="searchForm.CheckDateRange" type="date" @change="GetCheckCourse"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            placeholder="打卡时间" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="课程">
                        <el-select v-model="searchForm.CheckSettingId" placeholder="请选择课程">
                            <el-option
                                v-for="item in courseSelectList"
                                :key="item.Id"
                                :label="item.CourseName"
                                :value="item.Id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>

        </el-card>

        <!-- 导入对话框 -->
        <el-dialog title="导入数据" :visible.sync="importDialogVisible" width="30%">
            <el-upload class="upload-demo" ref="upload" action="" :auto-upload="false" :on-change="handleUploadChange"
                :file-list="fileList" accept=".xlsx,.xls" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="importDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitImport">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="打卡记录编辑对话框" :visible.sync="editorShow" width="80%" :lock-scroll="true" height="800px">
            <el-form v-if="editorShow == true" ref="editModalForm" :rules="editModalFormRules" :model="formData"
                label-width="140px" size="mini">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="用户" prop="UserId">
                            <el-paged-select url="/User/List" columnName="Name" columnValue="Id"
                                v-model="formData.UserId">
                            </el-paged-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="班级" prop="OrganizationId">
                            <el-paged-select url="/Organization/List" columnName="Name" columnValue="Id"
                                v-model="formData.OrganizationId">
                            </el-paged-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="经度" prop="Longitude">
                            <el-input v-model.trim="formData.Longitude"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纬度" prop="Latitude">
                            <el-input v-model.trim="formData.Latitude"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="人脸图片" prop="FaceImageUrl">
                            <el-input v-model.trim="formData.FaceImageUrl"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否迟到" prop="IsLate">
                            <el-switch v-model="formData.IsLate">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="有效开始时间" prop="BeginTime">
                            <el-date-picker v-model="formData.BeginTime" align="right" type="datetime"
                                placeholder="选择有效开始时间时间" value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="有效截止时间" prop="EndTime">
                            <el-date-picker v-model="formData.EndTime" align="right" type="datetime"
                                placeholder="选择有效截止时间时间" value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row type="flex" justify="end" align="bottom">
                    <el-form-item>
                        <el-button type="primary" plain @click="CreateOrEditForm()">确 定</el-button>
                        <el-button @click="editorShow = false">取 消</el-button>
                    </el-form-item>
                </el-row>
            </el-form>

        </el-dialog>


        <data-table ref="tableId" url="/CheckRecord/List" :column="dataColum">
            <template v-slot:header>
                <!-- <el-button type="primary" plain icon="el-icon-edit" @click="ShowEditModal()">新 增</el-button> -->
                <el-button type="danger" plain icon="el-icon-delete" @click="ShowBatchDeleteModal()">批 量 删 除</el-button>
            </template>
            <template v-slot:operate="scope">
                <!-- <el-button type="text" @click="ShowEditModal(scope.row.Id)">修 改</el-button> -->
                <el-button type="text" @click="ShowDeleteModal(scope.row.Id)">删 除</el-button>
            </template>
            <template v-slot:CheckSettingId="scope">
                {{courseList.find(item => item.Id == scope.row.CheckSettingId).CourseName}}
            </template>
            <template v-slot:CheckType="scope">
                {{ scope.row.CheckType === 'face' ? '人脸打卡' :
                   scope.row.CheckType === 'normal' ? '直接打卡' :
                   scope.row.CheckType === 'location' ? '位置打卡' :
                   scope.row.CheckType === 'qrcode' ? '扫码打卡' : scope.row.CheckType }}
            </template>
        </data-table>
    </div>
</template>

<script>
import store from '@/store';
import { mapGetters } from 'vuex'
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

export default {
    name: "CheckRecordList",
    computed: {
        ...mapGetters([
            'name', 'roleTypeFormat', 'avatar', 'userId', 'loginTimePeriod', "user", 'userId', 'roleType'
        ])
    },
    data() {

        return {
            lock: 0,//用来防止重复提交的变量
            searchForm: {},//搜索定义的数据对象
            importDialogVisible: false,
            fileList: [],
            uploadFile: null,
            courseList: [],
            courseSelectList: [],
            dataColum: [
                {
                    key: "Id",
                    hidden: true,

                },
                {
                    key: "UserId",
                    hidden: true,
                },
                {
                    key: "UserDto.Name",
                    title: "用户",
                    type: store.getters.columnType.SHORTTEXT,
                },
                {
                    key: "OrganizationId",
                    hidden: true,
                },
                {
                    key: "OrganizationDto.Name",
                    title: "班级",
                    type: store.getters.columnType.SHORTTEXT,
                },
                {
                    key: "Longitude",
                    title: "经度",
                    type: store.getters.columnType.SHORTTEXT,
                },
                {
                    key: "Latitude",
                    title: "纬度",
                    type: store.getters.columnType.SHORTTEXT,
                },
                {
                    key: "FaceImageUrl",
                    title: "人脸图片",
                    type: store.getters.columnType.IMAGES,
                },
                {
                    key: "CheckDate",
                    title: "打卡时间",
                    type: store.getters.columnType.SHORTTEXT,
                },
                {
                    key: "CheckSettingId",
                    title: "打卡课程",
                    type: store.getters.columnType.CUSTOM,
                },
                {
                    key: "CheckType",
                    title: "签到类型",
                    type: store.getters.columnType.CUSTOM,
                },
                {
                    title: "操作",
                    width: "300px",
                    type: store.getters.columnType.USERDEFINED,
                },
            ],
            editModalFormRules: {
                "UserId": [
                ],

                "OrganizationId": [
                ],

                "Longitude": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],

                "Latitude": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],

                "FaceImageUrl": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],

                "CheckDate": [
                ],

                "IsLate": [
                    { required: true, message: '该项为必填项', trigger: 'blur' },
                ],

                "BeginTime": [
                ],

                "EndTime": [
                ],

            },
            formData: {

            },//保存或者修改定义的数据对象
            editorShow: false,//编辑弹窗定义的数据对象

        };
    },
    mounted() {
        this.GetSelectList();
    },
    methods: {
        /**
         * 点击新增或者编辑的时候会触发
         */
        async ShowEditModal(Id) {

            let { Data } = await this.$Post(`/CheckRecord/Get`, { Id: Id });
            this.formData = Data;
            this.formData.Behavior = null;
            this.formData.IsEdit = Id != undefined;

            this.editorShow = true;

        },
        /**
         * 点击保存的时候会触发
         */
        async CreateOrEditForm() {
            if (this.lock == 1) return;
            this.$refs.editModalForm.validate(async valid => {
                if (valid) {
                    this.lock = 1;
                    var { Success } = await this.$PostLoading(`/CheckRecord/CreateOrEdit`, this.formData);
                    this.lock = 0;
                    if (Success) {
                        this.editorShow = false;
                        this.$refs.tableId.reload();
                    }
                }
            })
        },
        /**
         * 单个删除的时候会触发
         */
        async ShowDeleteModal(Id) {
            await this.$PostDelete(`/CheckRecord/Delete`, { Id: Id });
            this.$refs.tableId.reload();
        },
        /**
         * 批量删除的时候会触发
         */
        async ShowBatchDeleteModal() {
            var ids = this.$refs.tableId.GetSelectionRow().map(x => x.Id);
            await this.$PostDelete(`/CheckRecord/BatchDelete`, { Ids: ids });
            this.$refs.tableId.reload();
        },
        /**
         * 点击表格搜索按钮会触发
         */
        async TableSearch() {
            this.$refs.tableId.reload(this.searchForm);
        },
        /**
         * 点击清空表单会触发
         */
        async Reset() {
            this.searchForm = {};
            this.$refs.tableId.reload(this.searchForm);
        },

        // 处理导入按钮点击
        handleImport() {
            this.importDialogVisible = true;
            this.fileList = [];
        },

        // 处理文件上传变化
        handleUploadChange(file, fileList) {
            this.uploadFile = file;
            this.fileList = fileList.slice(-1); // 只保留最新上传的文件
        },

        // 提交导入
        async submitImport() {
            if (!this.uploadFile) {
                this.$message.warning('请先选择文件');
                return;
            }

            try {
                const data = await this.readExcel(this.uploadFile.raw);
                // 这里可以添加数据验证逻辑

                // 发送到后端处理
                const { Success, Message } = await this.$PostLoading('/CheckRecord/Import', { data });
                if (Success) {
                    this.$message.success('导入成功');
                    this.importDialogVisible = false;
                    this.$refs.tableId.reload();
                } else {
                    this.$message.error(Message || '导入失败');
                }
            } catch (error) {
                console.error('导入失败:', error);
                this.$message.error('导入失败: ' + error.message);
            }
        },

        // 读取Excel文件
        readExcel(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();

                reader.onload = (e) => {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        const jsonData = XLSX.utils.sheet_to_json(worksheet);
                        resolve(jsonData);
                    } catch (error) {
                        reject(error);
                    }
                };

                reader.onerror = (error) => {
                    reject(error);
                };

                reader.readAsArrayBuffer(file);
            });
        },
        async GetSelectList() {
            let { Data } = await this.$Post(`/CheckSetting/GetSelectList`);
            this.courseList = Data;
            console.log("---", this.courseList);
        },
        async GetCheckCourse() {
            let { Data } = await this.$Post(`/CheckSetting/GetCheckCourseList`, {
                BeginDate: this.searchForm.CheckDateRange,
                OrganizationId: this.searchForm.OrganizationId
            });
            this.courseSelectList = Data;
            console.log("---", this.courseSelectList);
        },
        // 处理导出按钮点击
        // 处理导出按钮点击
        async handleExport() {
            try {
                // 从后端获取所有数据（不带分页）
                const response = await this.$Post('/CheckRecord/List', {
                    ...this.searchForm,
                    PageIndex: 1,
                    PageSize: 999999 // 获取足够大的数据量
                });

                // 处理可能的嵌套数据结构
                let exportData = response.Data;
                // 如果数据嵌套在Items属性中（根据您的注释）
                if (exportData && exportData.Items) {
                    exportData = exportData.Items;
                }

                console.log("导出数据:", exportData);

                if (!exportData || exportData.length === 0) {
                    this.$message.warning('没有数据可导出');
                    return;
                }

                // 准备导出的数据
                const excelData = exportData.map(item => {
                    return {
                        '用户ID': item.UserId || '',
                        '用户姓名': item.UserDto?.Name || '',
                        '班级ID': item.OrganizationId || '',
                        '班级名称': item.OrganizationDto?.Name || '',
                        '经度': item.Longitude || '',
                        '纬度': item.Latitude || '',
                        '打卡时间': item.CheckDate || '',
                        '是否迟到': item.IsLate ? '是' : '否',
                        '有效开始时间': item.BeginTime || '',
                        '有效截止时间': item.EndTime || '',
                        '人脸图片URL': item.FaceImageUrl || '',
                        '创建时间': item.CreationTime || '',
                        '创建人ID': item.CreatorId || ''
                    };
                });

                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                const worksheet = XLSX.utils.json_to_sheet(excelData);

                // 设置列宽（可选）
                const colWidths = [
                    { wch: 10 }, // 用户ID
                    { wch: 15 }, // 用户姓名
                    { wch: 10 }, // 班级ID
                    { wch: 15 }, // 班级名称
                    { wch: 12 }, // 经度
                    { wch: 12 }, // 纬度
                    { wch: 20 }, // 打卡时间
                    { wch: 10 }, // 是否迟到
                    { wch: 20 }, // 有效开始时间
                    { wch: 20 }, // 有效截止时间
                    { wch: 40 }, // 人脸图片URL
                    { wch: 20 }, // 创建时间
                    { wch: 12 }  // 创建人ID
                ];
                worksheet['!cols'] = colWidths;

                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, '打卡记录');

                // 生成Excel文件并下载
                const excelBuffer = XLSX.write(workbook, {
                    bookType: 'xlsx',
                    type: 'array',
                    cellStyles: true // 启用样式
                });

                const blob = new Blob([excelBuffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });

                // 生成文件名，包含当前日期时间
                const now = new Date();
                const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
                FileSaver.saveAs(blob, `打卡记录_${dateStr}.xlsx`);

                this.$message.success('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败: ' + (error.message || '请检查数据或网络连接'));
            }
        }
    },
};
</script>

<style scoped>
.upload-demo {
    text-align: center;
}
</style>